package club.baimahu.pencil.servlet;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleServletHandler extends ChannelInboundHandlerAdapter {

    Logger logger = LoggerFactory.getLogger(SimpleServletHandler.class);

    private HttpServlet httpServlet;

    public SimpleServletHandler(HttpServlet httpServlet){
        this.httpServlet = httpServlet;
    }

    public void channelRead(ChannelHandlerContext ctx , Object msg) {
        if(msg instanceof FullHttpRequest){
            FullHttpRequest req = (FullHttpRequest) msg;
            HttpServletRequest request = new HttpServletRequest(ctx,req);
            HttpServletResponse response = new HttpServletResponse(ctx,req);

            Handler handler = this.httpServlet.getHandler(request);
            if(handler == null){
                ctx.writeAndFlush(get404Response());
                ctx.close();
                return;
            }else {
                handler.handle(request, response);
            }
        }
    }

    public void channelReadComplete(ChannelHandlerContext ctx)  {
        logger.info("channelReadComplete");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx)  {
        logger.info("channelInactive");

    }

    @SneakyThrows
    public DefaultHttpResponse get404Response(){
        String html = "<html><h1>404 Not Found</h1></html>";
        DefaultFullHttpResponse _404Response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND,Unpooled.wrappedBuffer(html.getBytes("utf-8")));
        _404Response.headers().set("Content-Type","text/html");
        return _404Response;
    }
}
